// 生成唯一的客户端ID
function generateUUID() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

const Client_ID = generateUUID();

chrome.runtime.onInstalled.addListener(() => {
  console.log('jobHelper installed Client_ID Init',Client_ID);

  //做一个安装技术统计
  chrome.storage.local.get(['jobHelper_installed_flag'], function(result) {
    if(!result['jobHelper_installed_flag']){
      chrome.storage.local.set({'jobHelper_installed_flag': Client_ID}, function() {
         trackEvent('jobHelper installed', {Client_ID:Client_ID });
      });
    }else{
      console.log(result['jobHelper_installed_flag']);
    }
  });
}
);

async function trackEvent(event, properties = {}) {
  const token = 'fb4a0ff71b5c88dd06e5cc41c50fd8cf'; // 替换为你的项目token
  const endpoint = 'https://api.mixpanel.com/track';

  // 构建事件数据对象
  const eventData = {
      event,
      properties: {
          ...properties,
          token,
      }
  };

  try {
      // 将事件数据转换为JSON字符串
      const jsonEventData = JSON.stringify(eventData);

      // 发送POST请求
      const response = await fetch(endpoint, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams({
              data: btoa(jsonEventData) // 使用Base64编码
          }).toString()
      });

      if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
      }

      console.log('Event tracked successfully');
  } catch (error) {
      console.error('Failed to track event:', error);
  }
}


chrome.action.onClicked.addListener((tab) => {
  //chrome.tabs.create({ url: 'pages/login.html' });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "responseBody") {
    console.log("Response Body:", message.body);
  }
});


// background.js (作为Service Worker)
self.addEventListener('fetch', async (event) => {
  try {
    const response = await event.respondWith(fetch(event.request));
    
    // 克隆响应以读取其内容而不破坏原始响应流
    const clone = response.clone();
    clone.text().then(text => {
      console.log('Response content:', text);
    });

    // 返回原始响应
    return response;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
});


// 监听来自 content.js 的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "getCookies") {
    // 获取指定域名的所有 cookies
    chrome.cookies.getAll(request.params, function(cookies) {
      sendResponse({ cookies: cookies });
    });
    return true; // 表示异步发送响应
  }
});



// 读取指定域名的所有 cookies
function readCookies() {
  chrome.cookies.getAll({ url: "https://liepin.com/" }, function(cookies) {
    if (cookies.length > 0) {
      console.log("Cookies found:");
      cookies.forEach(cookie => {
        console.log(cookie.name + " = " + cookie.value);
      });
    } else {
      console.log("No cookies found.");
    }
  });
}

// 调用读取 cookies 的函数
//readCookies();
